package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.controller.CommonJumpController;
import com.cardbaobao.cardbabyclient.model.Banner;
import com.cardbaobao.cardbabyclient.model.UserBindCards;
import com.cardbaobao.cardbabyclient.model.result.BannerResult;
import com.cardbaobao.cardbabyclient.model.result.UserBindCardsResult;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.AgreementWebViewActivity;
import com.cardbaobao.cardbabyclient.ui.adapter.CreditRepaymentAdapter;
import com.cardbaobao.cardbabyclient.ui.pop.CustomPopWin;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.DensityUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.cardbaobao.cardbabyclient.widget.divider.VerticalItemDecoration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Description: 信用卡还款列表
 * Created by FHW
 * on 2017/11/7
 */

public class CreditRepaymentActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    TitleBar title_bar;
    @BindView(R.id.recycler_view)
    RecyclerView recycler_view;

    private List<CreditRepaymentAdapter.RepaymentObject> itemDataList;
    private CreditRepaymentAdapter adapter;

    private CustomPopWin popwin;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_credit_repayment;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

        mCurrentPageId=Self.Page.app_repayment_homePage;

        title_bar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        title_bar.setRightViewListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SelfUtils.buriedClickData(Self.Action.app_click_repayment_topicon_add_creditcard,
                        Self.Action.app_click_repayment_topicon_add_creditcard_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                toAddCreditCard();
            }
        });
        title_bar.setRightView1Listener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopView();
            }
        });

        LinearLayoutManager layoutManager =
                new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        recycler_view.setLayoutManager(layoutManager);
        VerticalItemDecoration decoration =
                new VerticalItemDecoration(0, DensityUtil.dp2px(15));
        recycler_view.addItemDecoration(decoration);

    }

    @Override
    protected void onResume() {
        super.onResume();
        getCreditData();
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        itemDataList = new ArrayList<>();

//        itemDataList.add(new CreditRepaymentAdapter.RepaymentObject(CreditRepaymentAdapter.TYPE_ADD_CARD, null));
//        itemDataList.add(new CreditRepaymentAdapter.RepaymentObject(CreditRepaymentAdapter.TYPE_AD, new Banner.CarouselFigureListBean()));
//        for (int i = 0, size = 5; i < size; i++) {
//            itemDataList.add(
//                    new CreditRepaymentAdapter.RepaymentObject(CreditRepaymentAdapter.TYPE_ITEM, new UserBindCards.CreditCard()));
//        }
        adapter = new CreditRepaymentAdapter(mContext, itemDataList);
        adapter.setRepaymentItemClicked(new CreditRepaymentAdapter.RepaymentItemClicked() {
            @Override
            public void onItemPositionClicked(CreditRepaymentAdapter.RepaymentObject object, int position) {
                switch (position) {
                    case CreditRepaymentAdapter.RepaymentItemClicked.POSITION_ADD_CARD:
                        //添加信用卡
                        SelfUtils.buriedClickData(Self.Action.app_click_repayment_add_creditcard,
                                Self.Action.app_click_repayment_add_creditcard_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                mPrePageId);
                        toAddCreditCard();
                        break;
                    case CreditRepaymentAdapter.RepaymentItemClicked.POSITION_ITEM_AD:
                        //点击广告
                        ToastUtil.showToast("广告");
                        Object adItem = object.getObject();
                        if (adItem instanceof Banner.CarouselFigureListBean) {
                            CommonJumpController c = new CommonJumpController(mContext);
                            Map<String, Object> extras = new HashMap<>();
                            extras.put(CommonJumpController.FROM_PAGE, "信用卡还款");
                            c.bannerJump((Banner.CarouselFigureListBean) adItem,
                                    extras);
                        }
                        break;
                    case CreditRepaymentAdapter.RepaymentItemClicked.POSITION_REPAYMENT:
                        //还款
                        SelfUtils.buriedClickData(Self.Action.app_click_repayment_credit_card_repay,
                                Self.Action.app_click_repayment_credit_card_repay_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                mPrePageId);
                        UserBindCards.CreditCard creditCard = (UserBindCards.CreditCard) object.getObject();
                        Intent intent = new Intent();
                        intent.setClass(mContext, NewRepaymentActivity.class);
                        intent.putExtra("userName", creditCard.getUser_name());
                        intent.putExtra("bankName", creditCard.getCard_type_name());
                        intent.putExtra("cardNumber", creditCard.getCredit_card_no());
                        intent.putExtra("picUrl", creditCard.getPicture());
                        intent.putExtra("cardId", creditCard.getId());
                        intent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                        startActivity(intent);
                        break;
                }
            }
        });
        recycler_view.setAdapter(adapter);
    }

    private void toAddCreditCard() {
        Intent intent = new Intent();
        intent.setClass(mContext, NewAddCreditCardActivity.class);
        intent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
        startActivity(intent);
    }

    private void showPopView() {
        final View popView = LayoutInflater.from(this).inflate(R.layout.pop_credit_repayment, null, false);

        TextView tv_recording = (TextView) popView.findViewById(R.id.tv_recording);
        TextView tv_loan = (TextView) popView.findViewById(R.id.tv_loan);
        TextView tv_use_help = (TextView) popView.findViewById(R.id.tv_use_help);

        if (popwin == null) {
            popwin = new CustomPopWin(this, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0.8f);
        }
        popwin.setFocusable(true);
        popwin.setContentView(popView);
        popwin.showAsDropDown(title_bar, 0, 0, Gravity.RIGHT);

        tv_recording.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SelfUtils.buriedClickData(Self.Action.app_click_repayment_repay_record,
                        Self.Action.app_click_repayment_repay_record_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                Intent intent = new Intent();
                intent.setClass(CreditRepaymentActivity.this, RepaymentRecordActivity.class);
                intent.putExtra("credit_card_no", "");
                intent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                startActivity(intent);
                popwin.dismiss();
            }
        });
        tv_loan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SelfUtils.buriedClickData(Self.Action.app_click_repayment_cash_loan,
                        Self.Action.app_click_repayment_cash_loan_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                Uri content_url = Uri.parse(URLUtil.CASH_LOAN);
                intent.setData(content_url);
                startActivity(intent);
                popwin.dismiss();
            }
        });
        tv_use_help.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SelfUtils.buriedClickData(Self.Action.app_click_repayment_usage_help,
                        Self.Action.app_click_repayment_usage_help_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                initIntent();
                mIntent.setClass(mContext, AgreementWebViewActivity.class);
                mIntent.putExtra(AgreementWebViewActivity.WEB_TITLE_S, "信用卡还款常见问题");
                mIntent.putExtra(AgreementWebViewActivity.WEB_URL_S, URLUtil.USE_HELP_AGREEMENT);
                mIntent.putExtra(AgreementWebViewActivity.WEB_TYPE_I, 13);
                mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                startActivity(mIntent);
                popwin.dismiss();
            }
        });

    }

    private void getCreditData() {
        showProgressDialog(false);
        Api.getCreditData(String.valueOf(mApplication.getUser().getID()))
//        Api.getCreditData("5001787")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        dismissProgressDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissProgressDialog();
                        ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                                getString(R.string.string_request_server_fail));
                    }

                    @Override
                    public void onNext(String s) {
                        UserBindCardsResult result = JsonUtil.json2Object(s, UserBindCardsResult.class);
                        if (result.getCode() == Constant.SUC_CODE) {
                            UserBindCards data = result.getData();
                            if (data != null) {
                                List<UserBindCards.CreditCard> temp = data.getRepaymentCardList();
                                itemDataList.clear();
                                if (temp != null && temp.size() > 0) {
                                    for (int i = 0, size = temp.size(); i < size; i++) {
                                        itemDataList.add(new CreditRepaymentAdapter.RepaymentObject(CreditRepaymentAdapter.TYPE_ITEM, temp.get(i)));
                                    }
                                }
                                if (itemDataList.size() == 0) {
                                    itemDataList.add(new CreditRepaymentAdapter.RepaymentObject(CreditRepaymentAdapter.TYPE_ADD_CARD, null));
                                }
                                adapter.notifyDataSetChanged();
                            } else {
                                dismissProgressDialog();
                            }
                        } else {
                            dismissProgressDialog();
                            ToastUtil.showToast(result.getMsg());
                        }
                        //加载广告
                        loadBanner();
                    }
                });
    }

    private void loadBanner() {
        Api.getBannerData(Constant.GLB0336).
                subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        dismissProgressDialog();
                        //加载广告失败
                    }

                    @Override
                    public void onNext(String s) {
                        BannerResult result = JsonUtil.json2Object(s, BannerResult.class);
                        if (result.getCode() == Constant.SUC_CODE) {
                            dismissProgressDialog();
                            Banner banner = result.getData();
                            if (banner != null) {
                                List<Banner.CarouselFigureListBean> list =
                                        banner.getCarousel_figure_list();
                                if (list != null && list.size() > 0) {
                                    itemDataList.add(new CreditRepaymentAdapter.RepaymentObject(CreditRepaymentAdapter.TYPE_AD, list.get(0)));
                                    adapter.notifyDataSetChanged();
                                }
                            }
                        } else {
                            dismissProgressDialog();
                        }
                    }
                });
    }

}
